<template>
  <div class="order-management-container">
    <div class="header">
      <h1>订单管理</h1>
    </div>
    
    <!-- 搜索和筛选区域 -->
    <div class="filter-section">
      <div class="filter-row">
        <el-input
          v-model="searchKeyword"
          placeholder="搜索订单号或用户ID"
          prefix-icon="Search"
          style="width: 300px; margin-right: 16px"
          @keyup.enter="fetchOrders"
        />
        
        <el-select
          v-model="statusFilter"
          placeholder="订单状态"
          style="width: 150px; margin-right: 16px"
          @change="fetchOrders"
        >
          <el-option label="全部" value="" />
          <el-option label="待支付" value="pending" />
          <el-option label="已支付" value="paid" />
          <el-option label="已发货" value="shipped" />
          <el-option label="已完成" value="delivered" />
          <el-option label="已取消" value="cancelled" />
        </el-select>
        
        <el-date-picker
          v-model="dateRange"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          style="width: 300px"
          value-format="YYYY-MM-DD"
          @change="fetchOrders"
        />
        
        <el-button type="primary" @click="fetchOrders" style="margin-left: 16px">
          搜索
        </el-button>
        
        <el-button @click="resetFilters" style="margin-left: 8px">
          重置
        </el-button>
      </div>
    </div>
    
    <!-- 订单表格 -->
    <div class="table-container">
      <el-table
        v-loading="loading"
        :data="orders"
        style="width: 100%"
        border
      >
        <el-table-column prop="id" label="订单编号" width="120" />
        <el-table-column prop="userId" label="用户ID" width="100" />
        <el-table-column prop="totalAmount" label="订单金额" width="120">
          <template #default="scope">¥{{ Number(scope.row.totalAmount).toFixed(2) }}</template>
        </el-table-column>
        <el-table-column prop="status" label="订单状态" width="120">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.status)">{{ getStatusText(scope.row.status) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="paymentMethod" label="支付方式" width="120" />
        <el-table-column prop="createdAt" label="创建时间" width="180">
          <template #default="scope">{{ formatDate(scope.row.createdAt) }}</template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="scope">
            <el-button type="text" size="small" @click="viewOrderDetail(scope.row.id)">
              详情
            </el-button>
            <el-button
              type="text"
              size="small"
              @click="showUpdateStatusDialog(scope.row)"
              :disabled="!canUpdateStatus(scope.row.status)"
            >
              更新状态
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    
    <!-- 分页 -->
    <div class="pagination">
      <el-pagination
        v-model:current-page="pagination.currentPage"
        v-model:page-size="pagination.pageSize"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="pagination.total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
    
    <!-- 更新状态弹窗 -->
    <el-dialog
      v-model="updateStatusDialogVisible"
      title="更新订单状态"
      width="500px"
    >
      <div v-if="currentOrder">
        <div class="order-info">
          <p>订单编号: {{ currentOrder.id }}</p>
          <p>当前状态: <el-tag :type="getStatusType(currentOrder.status)">{{ getStatusText(currentOrder.status) }}</el-tag></p>
        </div>
        
        <div class="update-form">
          <el-form :model="updateForm">
            <el-form-item label="新状态" prop="status" required>
              <el-select v-model="updateForm.status" placeholder="请选择新状态">
                <el-option
                  v-for="status in availableStatuses"
                  :key="status.value"
                  :label="status.label"
                  :value="status.value"
                />
              </el-select>
            </el-form-item>
            
            <el-form-item v-if="updateForm.status === 'shipped'" label="物流单号" prop="trackingNumber">
              <el-input v-model="updateForm.trackingNumber" placeholder="请输入物流单号" />
            </el-form-item>
          </el-form>
        </div>
      </div>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="updateStatusDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="updateOrderStatus">确认更新</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue';
import { ElMessage, ElLoading } from 'element-plus';
import { useRouter } from 'vue-router';
import { Search } from '@element-plus/icons-vue';
import { orderService } from '../../api/orderService';
import axiosInstance from '../../api/axiosInstance';

// 扩展订单接口以包含管理员视图所需字段
interface AdminOrder {
  id: number;
  userId: number;
  orderNumber: string;
  status: 'pending' | 'paid' | 'shipped' | 'delivered' | 'cancelled';
  totalAmount: string;
  subtotal: string;
  taxAmount: string;
  shippingAmount: string;
  paymentMethod: string;
  shippingAddress: string;
  billingAddress: string;
  trackingNumber: string | null;
  notes: string | null;
  createdAt: string;
  updatedAt: string;
  user?: {
    id: number;
    username: string;
    email: string;
    firstName: string;
    lastName: string;
  };
}

interface Pagination {
  currentPage: number;
  pageSize: number;
  total: number;
}

interface UpdateForm {
  status: string;
  trackingNumber: string;
}

interface StatusOption {
  value: string;
  label: string;
}

const router = useRouter();

// 订单数据
const orders = ref<AdminOrder[]>([]);
const loading = ref(false);
const pagination = reactive<Pagination>({
  currentPage: 1,
  pageSize: 20,
  total: 0
});

// 筛选条件
const searchKeyword = ref('');
const statusFilter = ref('');
const dateRange = ref<string[]>([]);

// 更新状态弹窗相关
const updateStatusDialogVisible = ref(false);
const currentOrder = ref<AdminOrder | null>(null);
const updateForm = reactive<UpdateForm>({
  status: '',
  trackingNumber: ''
});

// 根据当前状态计算可用状态选项
const availableStatuses = computed<StatusOption[]>(() => {
  if (!currentOrder.value) return [];
  
  const statusMap: Record<string, StatusOption[]> = {
    'pending': [
      { value: 'paid', label: '已支付' },
      { value: 'cancelled', label: '已取消' }
    ],
    'paid': [
      { value: 'shipped', label: '已发货' },
      { value: 'cancelled', label: '已取消' }
    ],
    'shipped': [
      { value: 'delivered', label: '已完成' }
    ]
  };
  
  return statusMap[currentOrder.value.status] || [];
});

// 获取订单列表
const fetchOrders = async () => {
  loading.value = true;
  
  try {
    const params: any = {
      page: pagination.currentPage,
      limit: pagination.pageSize
    };
    
    // 添加筛选条件
    if (statusFilter.value) {
      params.status = statusFilter.value;
    }
    
    if (dateRange.value.length) {
      params.startDate = dateRange.value[0];
      params.endDate = dateRange.value[1];
    }
    
    if (searchKeyword.value) {
      const keyword = searchKeyword.value.trim();
      if (!isNaN(Number(keyword))) {
        // 如果是数字，尝试作为订单ID或用户ID搜索
        const num = Number(keyword);
        params.id = num; // 订单ID
      } else {
        // 否则作为订单号搜索
        params.orderNumber = keyword;
      }
    }
    
    const response = await axiosInstance.get('/admin/orders', { params });
    orders.value = response.data.data.orders;
    pagination.total = response.data.data.pagination.total;
  } catch (error) {
    console.error('获取订单列表失败:', error);
    ElMessage.error('获取订单列表失败，请重试');
  } finally {
    loading.value = false;
  }
};

// 重置筛选条件
const resetFilters = () => {
  searchKeyword.value = '';
  statusFilter.value = '';
  dateRange.value = [];
  pagination.currentPage = 1;
  fetchOrders();
};

// 分页处理
const handleSizeChange = (size: number) => {
  pagination.pageSize = size;
  fetchOrders();
};

const handleCurrentChange = (current: number) => {
  pagination.currentPage = current;
  fetchOrders();
};

// 查看订单详情
const viewOrderDetail = (orderId: number) => {
  router.push(`/admin/order-detail/${orderId}`);
};

// 显示更新状态弹窗
const showUpdateStatusDialog = (order: AdminOrder) => {
  currentOrder.value = order;
  updateForm.status = '';
  updateForm.trackingNumber = order.trackingNumber || '';
  updateStatusDialogVisible.value = true;
};

// 更新订单状态
const updateOrderStatus = async () => {
  if (!currentOrder.value || !updateForm.status) {
    ElMessage.warning('请选择有效的状态');
    return;
  }
  
  // 如果选择发货但没有填写物流单号
  if (updateForm.status === 'shipped' && !updateForm.trackingNumber.trim()) {
    ElMessage.warning('发货状态需要填写物流单号');
    return;
  }
  
  try {
    const loadingInstance = ElLoading.service({
      lock: true,
      text: '更新中...',
      background: 'rgba(0, 0, 0, 0.7)'
    });
    
    const data = {
      status: updateForm.status
    };
    
    if (updateForm.status === 'shipped') {
      data['trackingNumber'] = updateForm.trackingNumber.trim();
    }
    
    await axiosInstance.patch(`/admin/orders/${currentOrder.value.id}/status`, data);
    
    ElMessage.success('订单状态更新成功');
    updateStatusDialogVisible.value = false;
    fetchOrders(); // 刷新订单列表
  } catch (error) {
    console.error('更新订单状态失败:', error);
    ElMessage.error('更新订单状态失败，请重试');
  } finally {
    ElLoading.service().close();
  }
};

// 判断是否可以更新状态
const canUpdateStatus = (status: string): boolean => {
  return ['pending', 'paid', 'shipped'].includes(status);
};

// 获取状态对应的标签类型
const getStatusType = (status: string): string => {
  const typeMap: Record<string, string> = {
    'pending': 'warning',
    'paid': 'primary',
    'shipped': 'info',
    'delivered': 'success',
    'cancelled': 'danger'
  };
  
  return typeMap[status] || 'default';
};

// 获取状态显示文本
const getStatusText = (status: string): string => {
  const textMap: Record<string, string> = {
    'pending': '待支付',
    'paid': '已支付',
    'shipped': '已发货',
    'delivered': '已完成',
    'cancelled': '已取消'
  };
  
  return textMap[status] || status;
};

// 格式化日期
const formatDate = (dateString: string): string => {
  const date = new Date(dateString);
  return new Intl.DateTimeFormat('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  }).format(date);
};

// 组件挂载时获取订单列表
onMounted(() => {
  fetchOrders();
});
</script>

<style scoped>
.order-management-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;
}

.header {
  margin-bottom: 24px;
}

.header h1 {
  font-size: 24px;
  font-weight: 600;
  margin: 0;
  color: #333;
}

.filter-section {
  background: #fff;
  padding: 16px;
  border-radius: 8px;
  margin-bottom: 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.filter-row {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 12px;
}

.table-container {
  background: #fff;
  border-radius: 8px;
  padding: 16px;
  margin-bottom: 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.pagination {
  background: #fff;
  padding: 16px;
  border-radius: 8px;
  text-align: right;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.order-info {
  margin-bottom: 20px;
  padding: 12px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.order-info p {
  margin: 8px 0;
}

.update-form {
  padding: 16px 0;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .order-management-container {
    padding: 12px;
  }
  
  .filter-row {
    flex-direction: column;
    align-items: stretch;
  }
  
  .filter-row > * {
    width: 100% !important;
    margin-right: 0 !important;
    margin-left: 0 !important;
  }
  
  .pagination {
    padding: 12px;
  }
  
  .el-pagination {
    justify-content: center;
  }
}
</style>